
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:core';
import 'package:image_picker/image_picker.dart';
import '../../../api/UpLoadApi.dart';
import '../../../utils/Settings.dart';
import '../../../utils/Utils.dart';
import '../../../utils/dio/DioMethod.dart';
import '../../../utils/dio/DioUtil.dart';
import '../../form/LFormLogic.dart';
import '../../get/MyController.dart'  hide FormData,MultipartFile;
import 'package:get/get.dart' hide FormData,MultipartFile;
import 'LFormFileUpState.dart';
import 'package:open_file/open_file.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:flutter_document_picker/flutter_document_picker.dart';
import 'package:dio/dio.dart';


class LFormFileUpLogic extends MyController{


  final state = LFormFileUpState();


  void init({required Map formItem,required Map formData,String? betweenSign,required String formTag,required String formType}){
    state.formItem = formItem;
    state.formData = formData;
    state.betweenSign = betweenSign??"";
    state.fileList=[];
    state.fileVal=[];
    state.imagePicker = ImagePicker();
    state.isShow = true;
    state.isPermiss = false;
    state.fileNameList = [];
    state.downFileProgress = {};
    state.savePath = "";
    state.formTag = formTag;
    state.formType = formType;

    //初始化真实文件路径
    initFileList();
  }

  @override
  void onClose() {
    EasyLoading.dismiss();
    DioUtil.getInstance().cancel();
    super.onClose();
  }

  void initFileList(){
    if(state.formItem["readonly"]!=true){
      state.isShow = true;
    }else{
      state.isShow = false;
    }

    if(!Utils.isEmpty(state.formData[state.formItem['field']])){
      state.fileList = state.formData[state.formItem['field']].toString().split(",");
      state.fileVal = state.formData[state.formItem['field']].toString().split(",");
    }

    for(int i=0;i<state.fileList.length;i++){
      state.fileList[i] = '${Settings.fileServer}/${state.fileList[i]}';
      state.fileNameList.add(state.fileList[i].substring(state.fileList[i].lastIndexOf("/")+1));
      // state.downFileProgress[state.fileNameList[i]]="√";
    }


    update();
  }

  createFileList(context){
    List<Widget> li = [];
    for(int i=0;i<state.fileNameList.length;i++){
      // int index = state.fileNameList[i].lastIndexOf(".");
      // if(index>15){
      //   state.fileNameList[i] = "...${state.fileNameList[i].substring(index-15)}";
      // }

      li.add(
          InkWell(
            onTap: (){
              downFile(context,i);
            },
            child: SizedBox(
              width: 240,
              child: Row(
                children: [
                  Expanded(
                    flex: 8,
                    child: Text(state.fileNameList[i],overflow: TextOverflow.fade),
                  ),
                  Expanded(
                    flex: 2,
                    child:Visibility(
                      visible: state.isShow,
                      child: IconButton(
                        icon: const Icon(Icons.delete_forever_rounded),
                        onPressed: () {
                          deleteFile(i);
                        },
                      ),
                    ),
                  ),
                  Visibility(
                    visible: state.downFileProgress[state.fileNameList[i]]!=null,
                    child: Expanded(
                      flex: 3,
                      child: TextButton(
                          onPressed: (){
                            openFile(i);
                          },
                          child: Text(state.downFileProgress[state.fileNameList[i]]??'')
                      ),
                    ),
                  )

                ],
              ),
            ),
          )
      );
    }
    return li;
  }

  /// 申请权限
  requestPermission() async {
    // var status = await Permission.camera.status;
    var status1 = await Permission.storage.status;
    // var status2 = await Permission.photos.status;
    if (status1 != PermissionStatus.granted) {
      var future = await [
        // Permission.camera,
        Permission.storage,
        // Permission.photos,
      ].request();
      for (final item in future.entries) {
        if (item.value != PermissionStatus.granted) {
          return false;
        }
      }
    }
    return true;
  }

  ///获取手机的存储目录路径
  getPhoneLocalPath(context) async {
    final directory = Theme.of(context).platform == TargetPlatform.android
        ? await getExternalStorageDirectory()
        : await getApplicationDocumentsDirectory();
    return directory?.path;
  }

  ///打开文件
  openFile(i)async{
    ///storage/emulated/0/Android/data/com.example.luoyangxiaofang/files/1677919768333_IMG_20230211_110902.jpg
    final result = await OpenFile.open('${state.savePath}/${state.fileNameList[i]}');
    // print(result.message);
  }

  ///下载文件
  downFile(context,i)async{
    if(state.downFileProgress[state.fileNameList[i]] !=null){
      return;
    }
    /// 申请写文件权限
    bool isPermiss =  await requestPermission();
    if(isPermiss){
      ///手机储存目录
      state.savePath = await getPhoneLocalPath(context);
      final savedDir = Directory(state.savePath);
      bool hasExisted = await savedDir.exists();
      if (!hasExisted) {
        savedDir.create();
      }

      dynamic res = await DioUtil.getInstance().download(state.fileList[i].toString(), '${state.savePath}/${state.fileNameList[i]}', method:DioMethod.get,onReceiveProgress: (int count, int data){
        if (data != -1) {
          ///当前下载的百分比例
          state.downFileProgress[state.fileNameList[i]]='${(count / data * 100).toStringAsFixed(0)}%';
          update();
        }
      });

      if(res.statusCode==200){
        state.downFileProgress[state.fileNameList[i]]="√";
        update();
      }else{
        state.downFileProgress.remove(state.fileNameList[i]);
        EasyLoading.showToast('文件下载失败');
        update();
      }
    }


  }

  upload(file)async{

    String fileName;
    if(file.runtimeType.toString()=="String"){
      //文件上传
      fileName = file.substring(file.lastIndexOf("/")+1);
      file = File(file);
    }else{
      fileName = file.name;
    }


    //判断文件是否重复
    if(state.fileNameList.contains(fileName)){
      EasyLoading.showToast('此文件已上传过');
      return;
    }
    FormData formdata = FormData.fromMap({
      "file": await MultipartFile.fromFile(file.path, filename: fileName)
    });
    EasyLoading.show(status: "上传中...");
    dynamic res = await UpLoadApi.fileUp(formdata,(int count, int data){
      //可以计算进度

    });
    EasyLoading.dismiss();
    if(res["success"]){
      state.fileNameList.add(fileName);
      state.fileList.add("${Settings.fileServer}/${res['message']}");
      state.fileVal.add(res['message']);
      state.formData[state.formItem['field']]=state.fileVal.join(",");
      if(state.formType==Settings.formType["表单"]){
        Get.find<LFormLogic>(tag: state.formTag).onChange({'field':'${state.formItem["field"]}${state.betweenSign}','val':state.fileVal.join(",")});
      }
      update();
    }else{
      EasyLoading.showToast(res["message"]);
    }
  }

  deleteFile(index){
    state.downFileProgress.remove(state.fileNameList[index]);
    state.fileList.removeAt(index);
    state.fileVal.removeAt(index);
    state.fileNameList.removeAt(index);
    state.formData[state.formItem['field']]=state.fileVal.join(",");
    if(state.formType==Settings.formType["表单"]){
      Get.find<LFormLogic>(tag: state.formTag).onChange({'field':'${state.formItem["field"]}${state.betweenSign}','val':state.fileVal.join(",")});
    }
    update();
  }

  Future<dynamic> showCustomModalBottomSheet(context) async {
    return showModalBottomSheet<dynamic>(
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      context: context,
      builder: (BuildContext context) {
        return Container(
          clipBehavior: Clip.antiAlias,
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20.0),
              topRight: Radius.circular(20.0),
            ),
          ),
          height: MediaQuery.of(context).size.height / 3.0,
          child: Column(children: [
            SizedBox(
              height: 50,
              child: Stack(
                textDirection: TextDirection.rtl,
                children: [

                  const Center(
                    child: Text('选择操作',style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16.0),),
                  ),
                  IconButton(
                      icon: const Icon(Icons.close),
                      onPressed: () {
                        Navigator.of(context).pop();
                      }),
                ],
              ),
            ),
            const Divider(height: 1.0),
            Expanded(
              child: GridView(
                  padding: const EdgeInsets.only(top: 10),
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 4, //横轴三个子widget
                      childAspectRatio: 1.3 //宽高比为1时，子widget
                  ),
                  children:<Widget>[
                    GestureDetector(
                        child: Column(
                          children: [
                            Image.asset("images/wenjianguanli.png",width: 45,height: 45,),
                            const SizedBox(height: 2,),
                            const Text("文件")
                          ],
                        ),
                        onTap: () async {
                          FlutterDocumentPickerParams? params = FlutterDocumentPickerParams(
                            // 允许选取的文件拓展类型，不加此属性则默认支持所有类型
                            // allowedFileExtensions: ['pdf', 'xls', 'xlsx', 'jpg', 'png', 'jpeg'],
                          );

                          String? path = await FlutterDocumentPicker.openDocument(params: params,);
                          if(!Utils.isEmpty(path)){
                            upload(path);
                          }
                          // Navigator.pop(context);
                        }

                    ),
                    GestureDetector(
                        child: Column(
                          children: [
                            Image.asset("images/paizhao.png",width: 45,height: 45,),
                            const SizedBox(height: 2,),
                            const Text("相机")
                          ],
                        ),
                        onTap: () async {
                          XFile? image = await state.imagePicker.pickImage(source: ImageSource.camera);
                          if (image != null){
                            upload(image);
                          }

                          // Navigator.pop(context);
                        }

                    ),
                    GestureDetector(
                      child: Column(
                        children: [
                          Image.asset("images/xiangce.png",width: 45,height: 45,),
                          const SizedBox(height: 2,),
                          const Text("相册")
                        ],
                      ),
                      onTap:()async{
                        //选择多个文件
                        // List<XFile>? images = await _imagePicker.pickMultiImage();
                        //
                        // if(images.length>maxImageCount){
                        //
                        //   return;
                        // }
                        //单个文件选择
                        XFile? image = await state.imagePicker.pickImage(source: ImageSource.gallery);
                        if (image != null){
                          upload(image);
                        }

                      } ,
                    )

                  ]
              ),
            ),
          ]),
        );
      },
    );
  }

  dynamic onValidator (){
    //非空验证
    if (state.formItem["required"] == true && (state.formData[state.formItem['field']]==null || state.formData[state.formItem['field']]=="")) {
      return "不能为空";
    }
    return null;
  }

}